package com.example.androidsx;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class rigister extends AppCompatActivity {
    private SQLcj db;
    private Button bt_dl, bt_zc;
    private EditText id, username, userpwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rigister);


        db = new SQLcj(this);


        initViews();


        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        bt_zc.setOnClickListener(v -> {
            try {
                startActivity(new Intent(rigister.this, zhuceye.class));
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "跳转失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });


        bt_dl.setOnClickListener(v -> attemptLogin());
    }

    private void initViews() {
        bt_dl = findViewById(R.id.bt_dl);
        bt_zc = findViewById(R.id.bt_zc);
        id = findViewById(R.id.dl_userid);
        username = findViewById(R.id.dl_username);
        userpwd = findViewById(R.id.dl_userpwd);
    }

    private void attemptLogin() {
        String idStr = id.getText().toString().trim();
        String usernameStr = username.getText().toString().trim();
        String passwordStr = userpwd.getText().toString().trim();


        if (usernameStr.isEmpty() || passwordStr.isEmpty()) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }



        if (db.validateLogin(idStr, usernameStr, passwordStr)) {
            if (idStr.isEmpty()){
                Toast.makeText(this,"账号登录成功,普通账号。",Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(this,ShopListActivity.class);
                startActivity(intent);

            }else {
                Toast.makeText(this,"账号登录成功,管理员账号",Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(this, ymbj.class);
                intent.putExtra("key_id",idStr);
                intent.putExtra("kay_name",usernameStr);
                startActivity(intent);

            }


            finish();
        } else {
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        if (db != null) {
            db.close();
        }
        super.onDestroy();
    }
}